package com.playcrab.adouban;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.admob.android.ads.*;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.playcrab.adouban.util.Constants;

public class Main extends BaseActivity {
	private static final String LOG_TAG = "Main";

	private static final int MENU_SCAN = Menu.FIRST + 1;
	private static final int MENU_SETTINGS = Menu.FIRST + 9;
	private static final int MENU_ABOUT = Menu.FIRST + 10;
	private static final int MENU_LOGOUT = Menu.FIRST + 11;
	private static final int MENU_EXIT = Menu.FIRST + 12;

	private static final String PACKAGE_NAME = "com.playcrab.adouban";

	/** Called when the activity is first created. */

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);
		
 		AdManager.setTestDevices( new String[] {
 				AdManager.TEST_EMULATOR, // Android emulator
 				"E83D20734F72FB3108F104ABC0FFC738", // My T-Mobile G1 Test Phone
 				} ); 

		Button searchButton = (Button) findViewById(R.id.search_button);
		final EditText queryText = (EditText) findViewById(R.id.query_text);

		final CharSequence[] items = { "书籍", "电影", "音乐" };

		AlertDialog.Builder builder = new AlertDialog.Builder(Main.this);
		builder.setTitle("选择搜索类型:");
		builder.setItems(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				Intent i = new Intent(Main.this, Tabs.class);
				if (item == 0) {
					i.putExtra("type", "book");
				} else if (item == 1) {
					i.putExtra("type", "movie");
				} else {
					i.putExtra("type", "music");
				}
				i.putExtra("q", queryText.getText().toString());
				startActivity(i);
			}
		});
		final AlertDialog search_type_option = builder.create();
		searchButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (queryText.getText().toString().trim().length() == 0) {
					Toast.makeText(
							getApplicationContext(),
							Main.this.getResources().getText(
									R.string.main_search_name),
							Toast.LENGTH_SHORT).show();
					return;
				}
				search_type_option.show();
			}
		});


		
		
		Bundle bundle = this.getIntent().getExtras();	
		if(bundle!=null){
			String event = bundle.getString("event");
			if (event != null && event.equals("scan")) {
				Intent intent = new Intent(
						"com.google.zxing.client.android.SCAN");
				startActivityForResult(intent, 0);
				return;
			}
		}

		checkLoggedin();
		InsertPanel();

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case MENU_SCAN: {
			Intent intent = new Intent("com.google.zxing.client.android.SCAN");
			startActivityForResult(intent, 0);
			return true;
		}
		case MENU_SETTINGS:{
			Intent i = new Intent(this, Settings.class);
		    startActivity(i);
			return true;
		}
		case MENU_ABOUT: {
			PackageInfo info;
			try {
				info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle(getString(R.string.title_about) + " v"
						+ info.versionName);
				builder.setMessage(getString(R.string.msg_about));
				builder.setIcon(R.drawable.icon);
				// builder.setPositiveButton(R.string.button_open_browser,
				// aboutListener);
				builder.setNegativeButton("关闭", null);
				builder.show();

			} catch (NameNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return true;
		}
		case MENU_LOGOUT: {
			SharedPreferences settings = getSharedPreferences(
					Constants.PREF_DOUBAN, 0);
			settings.edit().clear().commit();
			showAuthDialog();
			return true;
		}
		case MENU_EXIT: {
			finish();
			return true;
		}

		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu); 
		menu.add(0, MENU_SETTINGS, 0, "设置").setIcon(android.R.drawable.ic_menu_preferences)
				.setAlphabeticShortcut('S');

		menu.add(0, MENU_LOGOUT, 0, "注销").setIcon(
				android.R.drawable.ic_menu_crop)
				.setAlphabeticShortcut('L');

		menu.add(0, MENU_ABOUT, 0, "关于").setIcon(
				android.R.drawable.ic_menu_info_details).setAlphabeticShortcut(
				'A');

		menu.add(0, MENU_EXIT, 0, "退出").setIcon(android.R.drawable.ic_menu_close_clear_cancel)
				.setAlphabeticShortcut('X');
		return true;
	}

	@Override
	public void onResume() {
		Log.i(LOG_TAG, "onResume");
		super.onResume();

	}

	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == 0) {

			if (resultCode == RESULT_OK) {
				ProgressDialog progressDialog = ProgressDialog.show(Main.this,
						Main.this.getResources().getText(R.string.waiting),
						Main.this.getResources().getText(R.string.searching),
						true);
				String contents = intent.getStringExtra("SCAN_RESULT");
				// String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
				// String contents = "9787532739011";
				String subject = null;
				String type = null;
				// Handle successful scan
				try {
					URL url = new URL("http://b.douban.com/search?q="
							+ contents);
					System.out.println("Before opening url connection ");
					HttpURLConnection httpConn = (HttpURLConnection) url
							.openConnection();
					httpConn.setInstanceFollowRedirects(true);
					httpConn.connect();
					int rcode = httpConn.getResponseCode();
					/*
					StringBuffer buffer = new StringBuffer();
					InputStream instream = httpConn.getInputStream();
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(instream));
					String line = null;
					while ((line = reader.readLine()) != null) {
						buffer.append(line);
						buffer.append("\n");
					}
					instream.close();*/
					URL final_url = httpConn.getURL();
					String content = final_url.toString();
					httpConn.disconnect();
					//Pattern p = Pattern.compile("302 Found");
					//Matcher m = p.matcher(content);
					//if (m.find()) {
					if (HttpURLConnection.HTTP_OK == rcode) {
						System.out.println("found it");
						Pattern p = Pattern.compile("/([a-z]+)/subject/([0-9]+)/");
						Matcher m = p.matcher(content);
						if (m.find()) {
							type = m.group(1);
							subject = m.group(2);
							System.out.println("The subject is: " + subject);
						}
					}
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				progressDialog.dismiss();
				if (subject != null) {
					Intent i = new Intent(this, ViewSubject.getViewClass(type));
					i.putExtra("id", subject);
					i.putExtra("type", type);
					startActivity(i);
				} else {
					Toast.makeText(getApplicationContext(),
							"对扫描结果[" + contents + "]查询失败", Toast.LENGTH_SHORT)
							.show();
				}
			} else if (resultCode == RESULT_CANCELED) {
				Toast.makeText(getApplicationContext(),
						"未能从 Barcode Scanner获取扫描结果", Toast.LENGTH_SHORT).show();
			}
		}
	}

	public void onStart() {
		super.onStart();
	}

	public void onStop() {
		super.onStop();
	}
}